<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="蛋糕名称" prop="cakeKnife">
            <el-input v-model="queryParams.cakeKnife" placeholder="请输入蛋糕名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['sj:cake:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['sj:cake:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['sj:cake:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['sj:cake:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="cakeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="主键" align="center" prop="id" v-if="true" /> -->
         <el-table-column label="蛋糕配置信息" align="center">
          <template #default="scope">
            <el-button plain type="success">简配配置</el-button>
            <el-button plain type="primary">中配配置</el-button>
            <el-button plain type="warning">高配配置</el-button>
          </template>
         </el-table-column>
        <el-table-column label="蛋糕名称" align="center" prop="cakeKnife" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新者名字" align="center" prop="updateByName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['sj:cake:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['sj:cake:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
    <!-- 添加或修改蛋糕类型对话框 -->
    <el-dialog class="modify-dialog" destroy-on-close :title="dialog.title" v-model="dialog.visible" width="500px"
      append-to-body>
      <el-form ref="cakeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="蛋糕名称" prop="cakeKnife">
          <el-input :disabled="!isDisable" v-model="form.cakeKnife" placeholder="请输入蛋糕名称" />
        </el-form-item>
        <el-form-item label="选择蛋糕类型" prop="cakeTypeId">
          <el-select v-model="form.cakeTypeId" class="m-2" placeholder="选择蛋糕类型">
            <el-option v-for="item in cakeType" :key="item.id" :label="item.cakeTypeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="整体图片" prop="cakeImagesIds">
          <image-upload v-model="form.cakeImagesIds" />
        </el-form-item>
        <el-form-item label="配件选择" prop="cakeCompositionBos">
          <el-tree draggable :data="baseMaterial" :props="props" node-key="id" :default-checked-keys="checkedKeys"
            show-checkbox @check="handleCheckNode">
          </el-tree>
        </el-form-item>
        <el-form-item label="必选配件" prop="cakeMaterialMustId">
          <el-select :disabled="!sortMaterial.length" multiple collapse-tags placeholder="选择配件顺序"
            v-model="requiredMaterial" @change="selectRequire">
            <el-option v-for="item in sortMaterial" :key="item.id" :label="item.materialName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="顺序" prop="cakeMaterialParentOrder">
          <el-select :disabled="!sortMaterial.length" multiple collapse-tags placeholder="选择配件顺序" v-model="orderSelect"
            @change="selectOrder">
            <el-option v-for="item in sortMaterial" :key="item.id" :label="item.materialName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="顺序展示">
          <el-collapse>
            <el-collapse-item title="顺序">
              <div v-for="(item, index) in nameOrder" :key="item">{{ index + 1 }}.{{ item }}</div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-show="isDisable">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Cake" lang="ts">
import type { FormInstance } from 'element-plus';
import { listCake, getCake, delCake, addCake, updateCake, cakeMaterial, materialAccessory } from '@/api/sj/cake';
import { CakeVO, CakeQuery, CakeForm, material, cakeCompositionBos } from '@/api/sj/cake/types';
import { CakeTypeVO, CakeTypeQuery } from "@/api/sj/cakeType/types";
import { listCakeType } from '@/api/sj/cakeType/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const isEdit = ref<boolean>(false);
const cakeList = ref<CakeVO[]>([]);
const baseMaterial = ref<material[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const cakeFormRef = ref<FormInstance>();
const checkedKeys = ref<string[]>([]);
const isDisable = ref(false);
const sortMaterial = ref<material[]>([]);
const orderSelect = ref<string[]>([]);
const requiredMaterial = ref<string[]>([]);
const nameOrder = ref<string[]>([]);
const cakeType = ref<CakeTypeVO[]>([]);
const queryCakeType = reactive<CakeTypeQuery>({
  cakeTypeName: '',
  pageNum: 1,
  pageSize: 999
});

const props = {
  label: 'materialName',
  children: 'children',
  id: 'cakeMaterialId'
};

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CakeForm = {
  id: undefined,
  cakeKnife: undefined,
  cakeCompositionIds: undefined,
  cakeCompositionBos: [],
  cakeMaterialParentOrder: undefined,
  cakeTypeId: undefined,
  cakeImagesIds: undefined,
  cakeMaterialMustId: undefined
}
/** 顺序必须全选的校验 */
const validateOrder = (rule: any, value: any, callback: any) => {
  const valueArray = value.split(',');
  if (valueArray.length != sortMaterial.value.length) {
    callback(new Error('父组件顺序时必须全部选择'));
  } else {
    callback();
  }
};

const data = reactive<PageData<CakeForm, CakeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cakeKnife: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    cakeKnife: [
      { required: true, message: "蛋糕名称不能为空", trigger: "blur" }
    ],
    cakeTypeId: [
      { required: true, message: "蛋糕类型不能为空", trigger: "blur" }
    ],
    cakeMaterialParentOrder: [
      { required: true, message: "父类顺序不能为空", trigger: "blur" },
      { validator: validateOrder, trigger: 'blur' }
    ],
    cakeCompositionBos: [
      { required: true, message: "蛋糕配件不能为空", trigger: "blur" }
    ],
    cakeMaterialMustId: [
      { required: true, message: "默认的配件不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getAccessoriesById = async (id: string) => {
  const accessories = await materialAccessory(id);
  return accessories.data
};

/**找出顶级配件 */
const findTopAccessories = (nodes: any[]) => {
  const idOfAccessories = nodes.map((item: any) => {
    return item.parentCakeId
  });
  sortMaterial.value = baseMaterial.value.filter((material: material) => {
    if (idOfAccessories.indexOf(material.id) != -1) {
      return material
    }
  });
};

/*选择树节点*/
const handleCheckNode = (checkedNodes: any, checkedKeys: any) => {
  const accessories = checkedKeys.checkedNodes;
  const result = accessories.filter((item: any) => {
    return item.children.length === 0
  });
  const compositions = result.map((item: any) => {
    return {
      cakeMaterialId: item.id,
      parentCakeId: item.topParentId,
      isDefault: false,
      cakeImagesId: '0'
    }
  });
  //找出选择的顶级配件
  const selectedTopAccessories = checkedKeys.checkedNodes.map((item: any) => {
    if (item.topParentId) {
      return item.topParentId
    }
    return 0
  });
  const sortTopAccessories = Array.from(new Set(selectedTopAccessories));
  sortMaterial.value = baseMaterial.value.filter((material: material) => {
    if (sortTopAccessories.indexOf(material.id) != -1) {
      return material
    }
  });
  //form.value.cakeCompositionBos = [...(form.value.cakeCompositionBos as cakeCompositionBos[]),...compositions];
  form.value.cakeCompositionBos = [...compositions];
}

/** 选择必须的配件 */
const selectRequire = () => {
  form.value.cakeMaterialMustId = requiredMaterial.value.join(',');
}


/** 选择配件的顺序 */
const selectOrder = () => {
  //将选中的顺序转换为字符串
  form.value.cakeMaterialParentOrder = orderSelect.value.join(',');
  //展示选中配件顺序名称的数组，只需要显示选中的配件的名字
  nameOrder.value = orderSelect.value.map((item: string) => {
    const nameSelected = sortMaterial.value.filter((material) => {
      return material.id == item;
    })
    return nameSelected[0].materialName;
  });
}

/** 查询蛋糕类型 */
const getCakeType = async () => {
  const res = await listCakeType(queryCakeType);
  cakeType.value = res.rows;
}

/** 查询基础材质 */
const getMaterial = async () => {
  const res = await cakeMaterial();
  const materials: material[] = res.data.filter((item: any) => {
    return item.parentId === 0
  });
  materials.forEach((item) => {
    const res = getAccessoriesById(item.id);
    res.then((res: material) => {
      item.children = res.children;
    });
  });
  // materialData.value = res.data;
  baseMaterial.value = materials;
};

/** 查询蛋糕类型列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCake(queryParams.value);
  cakeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  checkedKeys.value = [];
  orderSelect.value = [];
  nameOrder.value = [];
  // cakeFormRef.value?.resetFields();
  // console.log(cakeFormRef.value);
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: CakeVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 查看按钮操作 */
const handleView = async (row?: CakeVO) => {
  reset();
  isDisable.value = false;
  checkedKeys.value = [];
  const _id = row?.id || ids.value[0];
  const res = await getCake(_id);
  checkedKeys.value = res.data.compositionVos.map((item) => {
    return item.cakeMaterialId
  });
  const viewData = { cakeKnife: res.data.cakeKnife, id: _id, cakeCompositionBos: res.data.compositionVos };
  Object.assign(form.value, viewData);
  dialog.visible = true;
  dialog.title = "查看蛋糕类型";
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  sortMaterial.value = [];
  requiredMaterial.value = [];
  isDisable.value = true;
  dialog.visible = true;
  dialog.title = "添加蛋糕类型";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: CakeVO) => {
  reset();
  isDisable.value = true;
  checkedKeys.value = [];
  const _id = row?.id || ids.value[0];
  const res = await getCake(_id);
  const checkedIds = res.data.compositionVos.map((item) => {
    return item.cakeMaterialId
  });
  findTopAccessories(res.data.compositionVos);
  const orderArray = res.data.cakeMaterialParentOrder?.split(',');
  orderSelect.value = orderArray || [];
  form.value.cakeMaterialParentOrder = orderSelect.value.join(',');
  checkedKeys.value = checkedIds;
  nameOrder.value = orderSelect.value.map((item: string) => {
    const nameSelected = baseMaterial.value.filter((material) => {
      return material.id == item
    });
    return nameSelected[0].materialName
  });
  const updateData = {
    cakeKnife: res.data.cakeKnife,
    id: _id,
    cakeCompositionBos: res.data.compositionVos,
    cakeTypeId: res.data.cakeTypeId
  };
  Object.assign(form.value, updateData);
  dialog.visible = true;
  dialog.title = "修改蛋糕类型";
}


/** 提交按钮 */
const submitForm = () => {
  // const data = {...form.value,cakeMaterialParentOrder:orderSelect.value.join(',')};
  cakeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        const putData = { ...form.value };
        form.value.cakeCompositionBos?.forEach((item) => {
          item['cakeId'] = form.value.id
        });
        await updateCake(putData).finally(() => buttonLoading.value = false);
      } else {
        await addCake(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: CakeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除蛋糕类型编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delCake(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('sj/cake/export', {
    ...queryParams.value
  }, `cake_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getCakeType();
});
onBeforeMount(() => {
  getMaterial();
})
</script>
<style scoped lang="scss">
.modify-dialog {
  .el-form {
    max-height: 240px !important;
  }
}
</style>
